package edu.example.student.servlet;

import edu.example.manage.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/studentpage")
public class StudentPage extends HttpServlet {
    private static final JDBCUtils jdbcUtils = JDBCUtils.createConnection();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer integer = 0;
        try {
            integer = jdbcUtils.queryPageTotal("select count(1) form user where role = 0");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        Integer incr = Integer.valueOf(req.getParameter("incr"));
        HttpSession session = req.getSession(false);
        if (session == null) {
            session = req.getSession();
            session.setAttribute("stu_pages", 1);
            resp.sendRedirect("studentlist");
            return;
        }

        Object stu_pages = session.getAttribute("stu_pages");
        if (stu_pages != null) {
            if ((Integer) stu_pages <= 1 && incr < 0) {
                incr = 0;
            } else if ((Integer) stu_pages >= Math.ceil(integer / 20.0) && incr > 0) {
                incr = 0;
            }
            session.setAttribute("stu_pages", (Integer) stu_pages+incr);
        } else {
            session.setAttribute("stu_pages", 1);
        }

        resp.sendRedirect("studentlist");
    }
}
